import requests
from bs4 import BeautifulSoup
import tkinter as tk
from tkinter import scrolledtext
from datetime import datetime
import time
import pickle
import os
import json
import subprocess
import ctypes
import configparser

user_id = ''
sessionid = ''
steamLoginSecure = ''
api_url = ''

def get_urldata():
    try:
        response = requests.get(api_url)
        soup = BeautifulSoup(response.text, 'html.parser')
        element = soup.select_one('.profile_header_size')
        if element:
            miniprofile_value = element.get('data-miniprofile')
            global user_id
            user_id = miniprofile_value

            # print(miniprofile_value)
        else:
            print('未找到指定 class 的元素。')
            return
        if response.status_code == 200:
            headers = response.headers
            # print(f"headers {headers}")
            # 请求第二个接口
            get_steam_data(headers, miniprofile_value)
            return response.json()
        else:
            print(f"请求失败，状态码：{response.status_code}")
            # print_info(f"请求失败，状态码：{response.status_code}")
            return None
    except Exception as e:
        # print(f"发生错误：{e}")
        print(f"请求中...")
        # print_info(f"发生错误：{e}")
        return None

def get_steam_data(headers_from_first, miniprofile_value):
    try:
        # api_url = f"https://steamcommunity.com/miniprofile/{miniprofile_value}/json"
        api_url = f"https://steam-chat.com/miniprofile/{miniprofile_value}/json/?origin=https://steamloopback.hos"
        headers = {
            'Cookie': f'cookie=sessionid={sessionid};steamLoginSecure={steamLoginSecure}',
            'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
            'Accept': '*/*',
            'Host': 'steam-chat.com',
            'Connection': 'keep-alive'
        }
        # print("api_url----------------------------",api_url)
        # print("headers",headers)
        response = requests.get(api_url, headers=headers)
        if response.status_code == 200:
            data = response.json()
            if 'in_game' in data and 'rich_presence' in data['in_game']:
                rich_presence_value = data['in_game']['rich_presence']
                current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                print('当前时间:' f'{current_time}: 地图及比分: {rich_presence_value}\n')
            else:
                print("找不到 'rich_presence' 的值。")
            return response.json()
        else:
            print(f"请求失败，状态码：{response.status_code}")
            # print_info(f"请求失败，状态码：{response.status_code}")
            return None
    except Exception as e:
        # print(f"发生错误：{e}")
        print(f"请求中...")
        return None

# 读取配置文件中的 sessionid 和 steamLoginSecure
config = configparser.ConfigParser(interpolation=None)
config.read('config.ini')
sessionid = config.get('Credentials', 'sessionid', fallback='')
steamLoginSecure = config.get('Credentials', 'steamLoginSecure', fallback='')
api_url = config.get('Credentials', 'api_url', fallback='')

print('请输入目标网址，按回车开始')
input_url = input()
api_url = input_url
get_urldata()

while True:
    time.sleep(2)
    if user_id:
        get_steam_data(None, user_id)
    else:
        print("用户 ID 为空，无法继续请求。")